package com.example.tibetanmedicinechest.service.impl;

import com.example.tibetanmedicinechest.mapper.MedicineMapper;
import com.example.tibetanmedicinechest.mapper.UserMapper;
import com.example.tibetanmedicinechest.model.Content;
import com.example.tibetanmedicinechest.mapper.ContentMapper;
import com.example.tibetanmedicinechest.model.Medicine;
import com.example.tibetanmedicinechest.model.User;
import com.example.tibetanmedicinechest.service.IContentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.ObjectError;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 编程笨蛋
 * @since 2023-08-12
 */
@Service
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content> implements IContentService {
    @Autowired
    ContentMapper contentMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    MedicineMapper medicineMapper;
    @Override
    public List<Map<String, Object>> selectContentByUserId(int id) {
        List<Map<String, Object>> maps = contentMapper.selectContentByUserId(id);
        List<Map<String,Object>> datas = new ArrayList<>();

        for(Map<String,Object> map : maps){
            Map<String,Object> data = new HashMap<>();
            data.put("content",map.get("content"));
            User user = userMapper.selectById((Serializable) map.get("user_id"));
            Medicine medicine = medicineMapper.selectById((Serializable) map.get("medicine_id"));
            data.put("images",medicine.getImage());
            data.put("username",user.getName());
            data.put("name",medicine.getName());

            datas.add(data);
        }
        return datas;
    }

    @Override
    public List<Map<String, Object>> selectByMedicineId(int id) {
        List<Map<String, Object>> maps = contentMapper.selectByMedicineId(id);
        List<Map<String, Object>> datas = new ArrayList<>();
        for(Map<String,Object> map:maps){
            Map<String,Object> data = new HashMap<>();
            data.put("content",map.get("content"));
            User user = userMapper.selectById((Serializable) map.get("user_id"));
            data.put("username",user.getName());

            datas.add(data);
        }
        return datas;
    }

    @Override
    @Transactional
    public boolean addContent(Content content) {
        Integer count = contentMapper.addContent(content.getUser_id(), content.getMedicine_id(), content.getContent());
        if(count!=0) return true;
        else return false;
    }
}
